﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ajax.BLL;
using System.Runtime.Serialization;
using System.Text;
using System.Collections;
using System.IO;
using System.Globalization;

namespace Test.Controllers
{
	public class AdminiController : Controller
	{
		//
		// GET: /Admini/

		public ActionResult Index()
		{
			if (string.IsNullOrEmpty(Ticket.UserName))
			{
				return View("Login");
			}
			ViewData["username"] = Ticket.UserName;
			return View();
		}

		public ActionResult Login()
		{
			return View();
		}

		public ActionResult GoLogin(string name, string pwd)
		{
			if (name == "1" && pwd == "1")
			{
				Ticket.UserName = name;
				Ticket.LoginTime = DateTime.Now.ToShortTimeString();
				return Json(1, JsonRequestBehavior.AllowGet);
			}
			else
			{
				RedirectToAction("Login");
				return Json(2, JsonRequestBehavior.AllowGet);
			}
		}

		#region Products

		public ActionResult ProductClass()
		{
			ProductClass products = new ProductClass();
			List<Ajax.Model.ProductClass> list = products.GetModelList("");
			StringBuilder temp = new StringBuilder();
			foreach (var item in list)
			{
				if (item.Name.Length > 30)
				{
					item.Name = item.Name.Substring(0, 30) + "...";
				}
			}
			StringBuilder tmep2 = new StringBuilder();

			foreach (var item in list.Where(t => t.PID == null))
			{
				tmep2.AppendFormat("<option value='{1}'>{0}</option>", item.Name, item.ID);
				string temps = @"<li><span classID='{1}' tt='1'>{0}</span><ul>{2}</ul></li>";
				StringBuilder tt = new StringBuilder();
				foreach (var c in list.Where(t => t.PID == item.ID))
				{
					tt.AppendFormat("<li classID='{1}' tt='1'>{0}</li>", c.Name, c.ID);
				}
				temps = string.Format(temps, item.Name, item.ID, tt.ToString());
				temp.Append(temps);
			}
			ViewData["classData"] = temp.ToString();

			ViewData["FirstLevelClass"] = tmep2.ToString();

			return View();
		}

		public JsonResult AddProductClass(int id, string name, int pid)
		{
			Ajax.Model.ProductClass newclass = new Ajax.Model.ProductClass();
			ProductClass bll = new ProductClass();
			if (id != 0)
			{
				newclass.ID = id;
			}
			newclass.Name = name;
			if (pid != 0 && pid != null)
			{
				newclass.PID = pid;
			}
			if (id != 0)
			{
				bll.Update(newclass);
				// modify
			}
			else
			{
				bll.Add(newclass);
				newclass = bll.GetModel(bll.GetMaxId());
				//insert
			}
			return Json(newclass, JsonRequestBehavior.AllowGet);
		}

		public JsonResult DeleteProductClass(int id)
		{
			ProductClass c = new ProductClass();
			bool result = c.Delete(id);
			return Json(result, JsonRequestBehavior.AllowGet);
		}

		public JsonResult Getall()
		{
			ProductClass products = new ProductClass();
			List<Ajax.Model.ProductClass> list = products.GetModelList("");
			foreach (var item in list)
			{
				if (item.Name.Length > 30)
				{
					//item.Name = item.Name.Substring(0, 30) + "...";
				}
			}
			var result = from cc in list where cc.PID == null select new { text = cc.Name, id = cc.ID, children = (from ccc in list where ccc.PID == cc.ID select new { text = ccc.Name, id = ccc.ID }) };
			return Json(result, JsonRequestBehavior.AllowGet);
		}

		public ActionResult Products()
		{
			return View();
		}

		/// <summary>
		/// save products
		/// </summary>
		/// <param name="products">target</param>
		/// <returns></returns>
		[ValidateInput(false)]
		public JsonResult SaveProduct(int ID, int ClassID, int ShowIndex, int ShowIndexClass, string productName, string description)
		{
			Ajax.Model.Products products = new Ajax.Model.Products();
			products.ID = ID;
			products.ClassID = ClassID;
			products.ProductName = productName;
			products.ShowInClass = ShowIndexClass;
			products.ShowInIndex = ShowIndex;
			products.ImagePath = "";
			products.Description = description;
			Ajax.Model.Products newclass = new Ajax.Model.Products();
			Products bll = new Products();
			if (products.ID != 0)
			{
				bll.Update(products);
				newclass = bll.GetModel(products.ID);
			}
			else
			{
				bll.Add(products);
				newclass = bll.GetModel(bll.GetMaxId());
			}
			return Json(newclass, JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// delete product by id
		/// </summary>
		/// <param name="id">product id</param>
		/// <returns></returns>
		public JsonResult DeleteProduct(int id)
		{
			if (id == 0)
			{
				return Json(null, JsonRequestBehavior.DenyGet);
			}
			Products products = new Products();
			bool reuslt = products.Delete(id);
			return Json(reuslt, JsonRequestBehavior.AllowGet);
		}

		public ActionResult ProductDetail()
		{
			if (!string.IsNullOrEmpty(Request.QueryString["id"]))
			{
				ViewData["ID"] = Convert.ToInt16(Request.QueryString["id"].Replace("\'", ""));
			}
			if (!string.IsNullOrEmpty(Request.QueryString["classID"]))
			{
				ViewData["classID"] = Convert.ToInt16(Request.QueryString["classID"].Replace("\'", ""));
			}
			return View();
		}
		/// <summary>
		/// get product by class
		/// </summary>
		/// <param name="id">class id</param>
		/// <returns></returns>
		public JsonResult GetProductsByClass(int id)
		{
			Products products = new Products();
			return Json(products.GetModelList(" ClassID = " + id), JsonRequestBehavior.AllowGet);
		}


		#endregion

		#region Solutions

		public ActionResult SolutionClass()
		{
			return View();
		}
		/// <summary>
		/// all Products Class
		/// </summary>
		/// <returns></returns>
		public JsonResult GetAllClass()
		{
			ProductClass products = new ProductClass();
			List<Ajax.Model.ProductClass> list = new List<Ajax.Model.ProductClass>();
			list = products.GetModelList("");
			foreach (var item in list)
			{
				if (item.Name.Length > 40)
				{
					item.Name = item.Name.Substring(0, 40) + "...";
				}
			}
			return Json(list, JsonRequestBehavior.AllowGet);
		}
		/// <summary>
		/// all solution class
		/// </summary>
		/// <returns></returns>
		public JsonResult GetAllSolutionClass()
		{
			SolutionClass products = new SolutionClass();
			List<Ajax.Model.SolutionClass> list = new List<Ajax.Model.SolutionClass>();
			list = products.GetModelList("");
			return Json(list, JsonRequestBehavior.AllowGet);
		}
		/// <summary>
		/// all solution  
		/// </summary>
		/// <returns></returns>
		public JsonResult GetAllSolutions(int classID)
		{
			Solutions products = new Solutions();
			List<Ajax.Model.Solutions> list = new List<Ajax.Model.Solutions>();
			StringBuilder temp = new StringBuilder();
			if (classID != -1)
			{
				temp.AppendFormat("   classid={0} ", classID);
			}
			list = products.GetModelList(temp.ToString());
			return Json(list, JsonRequestBehavior.AllowGet);
		}
		public ActionResult Solution()
		{
			SolutionClass solution = new SolutionClass();
			var list = solution.GetModelList("");
			StringBuilder temp = new StringBuilder();
			foreach (var item in list)
			{
				temp.AppendFormat("<option value = '{0}'>{1}</option>", item.ID, item.ClassName);
			}
			ViewData["options"] = temp.ToString();
			return View();
		}

		public ActionResult SolutionEdit(int? id)
		{
			if (!string.IsNullOrEmpty(Request.QueryString["classID"]))
			{
				ViewData["classID"] = Request.QueryString["classID"].Replace("\'", "");
			}

			if (!string.IsNullOrEmpty(Request.QueryString["id"]))
			{
				ViewData["id"] = Request.QueryString["id"].Replace("\'", "");
			}
			SolutionClass solution = new SolutionClass();
			var list = solution.GetModelList("");
			StringBuilder temp = new StringBuilder();
			foreach (var item in list)
			{
				temp.AppendFormat("<option value = '{0}'>{1}</option>", item.ID, item.ClassName);
			}
			ViewData["options"] = temp.ToString();

			return View();
		}

		public JsonResult SaveSolutionClass(int id, string className)
		{
			Ajax.Model.SolutionClass cla = new Ajax.Model.SolutionClass();
			cla.ID = id;
			cla.ClassName = className;
			SolutionClass cll = new SolutionClass();

			if (id == 0)
			{
				cll.Add(cla);
				return Json(cll.GetModel(cll.GetMaxId()), JsonRequestBehavior.AllowGet);
			}
			else
			{
				cla.ID = id;
				cll.Update(cla);
				return Json(cla, JsonRequestBehavior.AllowGet);
			}
		}

		public JsonResult DeleteSolutionClass(int id)
		{
			SolutionClass cla = new SolutionClass();
			return Json(cla.Delete(id), JsonRequestBehavior.AllowGet);
		}

		public JsonResult DeleleSolution(int id)
		{
			Solutions cla = new Solutions();
			return Json(cla.Delete(id), JsonRequestBehavior.AllowGet);
		}
		public JsonResult GetSolutionByID(int id)
		{
			Solutions slu = new Solutions();
			return Json(slu.GetModel(id), JsonRequestBehavior.AllowGet);
		}

		[ValidateInput(false)]
		public JsonResult SaveSolution(int id, int showIndex, int classID, string title, int showInClass, string description)
		{
			Ajax.Model.Solutions cla = new Ajax.Model.Solutions();
			cla.ID = id;
			cla.Title = title;
			cla.UpdateTime = DateTime.Now;
			cla.Description = description;
			cla.ClassID = classID;
			cla.ShowInClass = showInClass;
			cla.ShowInIndex = showIndex;
			Solutions cll = new Solutions();

			if (id == 0)
			{
				cll.Add(cla);
				return Json(cll.GetModel(cll.GetMaxId()), JsonRequestBehavior.AllowGet);
			}
			else
			{
				cla.ID = id;
				cll.Update(cla);
				return Json(cla, JsonRequestBehavior.AllowGet);
			}
		}


		#endregion

		#region Reference

		public ActionResult Reference()
		{
			return View();
		}

		public ActionResult RefrenceEdit()
		{
			if (!string.IsNullOrEmpty(Request.QueryString["id"]))
			{
				ViewData["id"] = Request.QueryString["id"].Replace("\'", "");
			}

			return View();
		}

		public JsonResult GetReferenceByID(int id)
		{
			if (id == 0)
			{
				return Json(null, JsonRequestBehavior.DenyGet);
			}
			else
			{
				References bll = new References();
				return Json(bll.GetModel(id), JsonRequestBehavior.AllowGet);
			}
		}
		[ValidateInput(false)]
		public JsonResult SaveReference(int id, int year, string projectName, string city, string description)
		{
			References bll = new References();
			Ajax.Model.References model = new Ajax.Model.References();
			model.ID = id;
			model.RYear = year;
			model.ProjectName = projectName;
			model.City = city;
			model.Description = description;

			// add
			if (id == 0)
			{
				bll.Add(model);
				return Json(bll.GetModel(bll.GetMaxId()), JsonRequestBehavior.AllowGet);
			}
			// udpate
			else
			{
				bll.Update(model);
				return Json(model, JsonRequestBehavior.AllowGet);
			}

		}

		public JsonResult GetAllReference()
		{
			References bll = new References();
			return Json(bll.GetModelList(""), JsonRequestBehavior.AllowGet);
		}

		public JsonResult DeleteReference(int id)
		{
			if (id == 0)
			{
				return Json(null, JsonRequestBehavior.DenyGet);
			}
			References bll = new References();
			return Json(bll.Delete(id), JsonRequestBehavior.AllowGet);
		}

		#endregion


		#region FileUpload
		[HttpPost]
		public ActionResult UploadImage()
		{
			string savePath = "/upload/images/";
			string saveUrl = "/upload/images/";
			string fileTypes = "gif,jpg,jpeg,png,bmp";
			int maxSize = 1000000;
			Hashtable hash = new Hashtable();
			HttpPostedFileBase file = Request.Files["imgFile"];
			if (file == null)
			{
				hash = new Hashtable();
				hash["error"] = 0;
				hash["url"] = "请选择文件";
				return Json(hash);
			}
			string dirPath = Server.MapPath(savePath);
			if (!Directory.Exists(dirPath))
			{
				hash = new Hashtable();
				hash["error"] = 0;
				hash["url"] = "上传目录不存在";
				return Json(hash);
			}
			string fileName = file.FileName;
			string fileExt = Path.GetExtension(fileName).ToLower();
			ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(','));
			if (file.InputStream == null || file.InputStream.Length > maxSize)
			{
				hash = new Hashtable();
				hash["error"] = 0;
				hash["url"] = "上传文件大小超过限制";
				return Json(hash);
			}
			if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
			{
				hash = new Hashtable();
				hash["error"] = 0;
				hash["url"] = "上传文件扩展名是不允许的扩展名";
				return Json(hash);
			}
			string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
			string filePath = dirPath + newFileName;
			file.SaveAs(filePath);
			string fileUrl = saveUrl + newFileName;
			hash = new Hashtable();
			hash["error"] = 0;
			hash["url"] = fileUrl;
			return Json(hash, "text/html;charset=UTF-8"); ;
		}
		#endregion

	}
}
